import { remove } from 'lodash-es'

interface IGlobalStore {
  // 全局配置
  menucollapse: boolean // 菜单展开
  useTabs: boolean // 使用tabs
  // 分页
  pageSize: number
  // tabs
  allTabs: Array<string>
  groupOptions: {
    label: string
    value: string
  }[]
  activeTab: string
  tabDict: {
    [key: string]: string
  }
  // 验证码延时
  mailAwait: number
  mailAwaitEndTime: number
}

export const useGlobal = defineStore('global', {
  state: () => {
    const data = reactive<IGlobalStore>({
      menucollapse: false,
      useTabs: false,
      pageSize: 20,
      allTabs: [],
      groupOptions: [],
      activeTab: '',
      tabDict: {},
      mailAwait: 0,
      mailAwaitEndTime: 0,
    })

    // tab-移除tab页
    function removeTab(targetName: string) {
      const { activeTab, allTabs } = data
      if (activeTab === targetName) {
        const notHave = allTabs.every((name, index) => {
          if (name === targetName) {
            const nextTab = allTabs[index + 1] || allTabs[index - 1]
            if (nextTab) {
              data.activeTab = nextTab
              return false
            }
          }
          return true
        })
        if (notHave) data.activeTab = ''
      }
      remove(allTabs, (e: string) => e == targetName)
    }

    // tab-移除当前tab页
    function closeTab() {
      removeTab(data.activeTab)
    }

    async function openAwait(num: number) {
      data.mailAwait = num
      data.mailAwaitEndTime = Math.floor(Date.now() / 1000) + num
      let inter = setInterval(() => {
        if (data.mailAwait <= 0) {
          clearInterval(inter)
          return
        }
        data.mailAwait -= 1
      }, 1000)
    }

    onMounted(() => {
      const { mailAwait, mailAwaitEndTime } = data
      if (mailAwait) {
        const endDateTime = mailAwaitEndTime
        const now = Math.floor(new Date().getTime() / 1000)
        if (endDateTime > now) openAwait(endDateTime - now)
        else Object.assign(data, { mailAwait: 0, mailAwaitEndTime: 0 })
      }
    })

    return {
      ...toRefs(data),
      closeTab,
      removeTab,
      openAwait,
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'XXXXXXX-GLOBAL',
        storage: localStorage,
      },
    ],
  },
})
